package com.client.config;

import com.client.processor.SsoServerProcesssor;
import com.portal.sso.client.filter.WebAppFilter;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.server.JwtServerHander;
import com.portal.sso.core.server.RequestServerHandler;
import com.portal.sso.core.server.VerificationTgtServer;
import com.portal.sso.core.server.impl.JwtServerHanderImpl;
import com.portal.sso.core.server.impl.RequestServerHandlerImpl;
import com.portal.sso.core.server.impl.VerificationTgtServerImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class ClientSsoConfig implements DisposableBean {
    @Autowired
    SsoServerProcesssor ssoServerProcesssor;
    @Value("${portal.sso.server}")
    private String ssoServer;

    @Value("${portal.sso.logout.path}")
    private String ssoLogoutPath;

    @Value("${portal.sso.excluded.paths}")
    private String ssoExcludedPaths;


    @Bean
    public WebAppFilter webAppFilter(){
       return new WebAppFilter();
    }
    @Bean
    public RequestServerHandler requestServerHandler(){
        return new RequestServerHandlerImpl();
    }
    @Bean
    public VerificationTgtServer verificationTgtServer(){
        VerificationTgtServer server = new VerificationTgtServerImpl();
        server.setClientAppId(ssoServerProcesssor.getClientAppId());
        server.setClientSecret(ssoServerProcesssor.getClientSecret());
        server.setJwtServerHander(jwtServerHanderImpl());
        return server;
    }
    @Bean
    public JwtServerHander jwtServerHanderImpl(){
        return new JwtServerHanderImpl();
    }


    @Bean
    public FilterRegistrationBean PortalSsoFilterRegistration() {

        // 注册拦截器
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setName("WebAppFilter");
        registration.setOrder(1);
        registration.addUrlPatterns("/*");
        registration.setFilter(webAppFilter());
        registration.addInitParameter(SsoConfig.SSO_CLIENT_SERVER, ssoServer);
        registration.addInitParameter(SsoConfig.SSO_CLIENT_LOGOUT_PATH, ssoLogoutPath);
        registration.addInitParameter(SsoConfig.SSO_CLIENT_EXCLUDED_PATHS, ssoExcludedPaths);
        registration.addInitParameter(SsoConfig.SSO_APP_ID, ssoServerProcesssor.getClientAppId());
        //没有登录时，指定跳转地址，如果没有指定则默认使用认证中心的登录地址
        registration.addInitParameter(SsoConfig.SSO_SERVER_LOGIN_PATHS,ssoServerProcesssor.getLoginPath());
        return registration;
    }
    @Override
    public void destroy() throws Exception {
        log.debug("拦截器已执行完毕");
    }
}
